package cn.wolfcode.trip.app.controller;

import cn.wolfcode.trip.app.util.UserContext;
import cn.wolfcode.trip.base.domain.Travel;
import cn.wolfcode.trip.base.domain.TravelLike;
import cn.wolfcode.trip.base.domain.User;
import cn.wolfcode.trip.base.service.ITravelLikeService;
import cn.wolfcode.trip.base.service.ITravelService;
import cn.wolfcode.trip.base.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@RestController
@RequestMapping("/likes")
public class LikeController {

    @Autowired
    private ITravelLikeService travelLikeService;

    @Autowired
    private ITravelService travelService;

    /**
     * 点赞
     * @param travelId
     * @return
     */
    @PostMapping
    public JsonResult addLike(Long travelId){
        JsonResult jsonResult = new JsonResult();
        User currentUser = UserContext.getCurrentUser();

        //查询当前游记点赞数
        Integer likeCount = travelService.queryForLikeCount(travelId);

        //如果没有默认为0
        if (likeCount==null){
            likeCount = 0;
        }
        //通过游记id和当前登录用户id查询该用户在该游记是否有点赞记录
        TravelLike travelLike = travelLikeService.queryLike(travelId, currentUser.getId());
        if (travelLike==null){
            //没有则可以点赞,定义一个点赞对象保存
            TravelLike travelLike1 = new TravelLike();
            Travel travel = travelService.queryByTravelId(travelId);
            travelLike1.setTravel(travel);
            travelLike1.setUser(currentUser);
            travelLike1.setCreateTime(new Date());
            travelLike1.setStatus(TravelLike.UNREAD);
            travelLikeService.save(travelLike1);
            //同时游记中当前点赞数加一
            travelService.updateLikeCount(likeCount+1,travelId);
            return jsonResult;
        }else{
            String msg = "取消点赞";
            //如果已存在就删除这个记录,取消点赞
            travelLikeService.deleteLike(travelId,currentUser.getId());
            //对应的游记点赞数减一
            travelService.updateLikeCount(likeCount-1,travelId);
            return jsonResult.mark(msg);
        }
    }

    /**
     * 获取点赞数量(用作回显暂时未完善)
     * @param travelId
     * @return
     */
    @GetMapping
    public JsonResult getLike(Long travelId){
        JsonResult jsonResult = new JsonResult();
        User currentUser = UserContext.getCurrentUser();
        //必须有登录用户才需要去查询该用户是否点赞
        if (currentUser!=null){
            TravelLike travelLike = travelLikeService.queryLike(travelId, currentUser.getId());
            if (travelLike!=null){
                return jsonResult;
            }
        }
        return jsonResult.mark(new String("没有用户"));
    }

    /**
     *  将用户所有的阅读的 点赞记录修改为 已读
     * @param authorId
     * @return
     */
    @PutMapping
    public JsonResult updateState(Long authorId){
        JsonResult result = new JsonResult();
        travelLikeService.updateState(authorId);
        return result;
    }
}
